package ictbk.ttmk51.grapro.app.safefile;

import ictbk.ttmk51.grapro.app.LoginActivity;
import ictbk.ttmk51.grapro.app.R;
import ictbk.ttmk51.grapro.app.common.MyActivity;
import ictbk.ttmk51.grapro.app.service.GetWebservice;
import ictbk.ttmk51.grapro.app.utils.CheckFile;
import ictbk.ttmk51.grapro.app.utils.DateFormat;
import ictbk.ttmk51.grapro.app.utils.FileFolderProperties;
import ictbk.ttmk51.grapro.app.utils.FileStringBase64;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class SafeFile extends MyActivity {
	String path = Environment.getExternalStorageDirectory().getAbsolutePath();
	private List<String>directoryEntries = new ArrayList<String>();
	private List<String> item = new ArrayList<String>(); //Name of File and Folder
	private File currentDirectory = new File(path);
	private int							item_position_long_clicked;
	
	Handler								myHandler				= new Handler();
	
	private MediaPlayer mPlayer = new MediaPlayer();
	
	private ListView lv;
	private TextView titleManager;
	
	public SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_browser_screen);
        
        lv = (ListView)findViewById(R.id.list);
        
        browseTo(new File(path));
        
        ImageButton upLevelButton = (ImageButton)findViewById(R.id.upParentFolder);
        
        upLevelButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopPlayMusicFile();
				upOnLevel();
			}
		});
        
        onItemClick(lv);
    }
    
    //browse to parent directory
    private void upOnLevel(){
    	if(this.currentDirectory.getParent() != null){
    		this.browseTo(this.currentDirectory.getParentFile());
    	}
    }
    
    //browser to file or directory
    private void browseTo(final File aDirectory){
    	//if we want to browse directory
    	if(aDirectory.isDirectory()){
    		//fill list with files from this directory
    		this.currentDirectory = aDirectory;
    		fill(aDirectory.listFiles());
    		
    		//set titleManager text
    		titleManager = (TextView)findViewById(R.id.pathName);
    		titleManager.setText(aDirectory.getAbsolutePath());
    	}else {
    		
    		Toast.makeText(SafeFile.this, "Open file", Toast.LENGTH_LONG).show();
    	}
    }
    
    //fill list
    private void fill(final File[]files){
    	//clear list
    	directoryEntries.clear();
    	item.clear();
    	
    	for(File file:files){
    		directoryEntries.add(file.getAbsolutePath());
    		item.add(file.getName());
    	}
    	
    	//create array adapter to show everything
    	ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.list_folder_file, item){
    		@Override
			public View getView(int position, View v, ViewGroup parent) {
    			
				if(v == null){
					LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					v = vi.inflate(R.layout.list_folder_file, null);
				}
				
				//Check null exception
				Log.i("item Length: ",String.valueOf(item.size()));
				Log.i("dicrectoryEntries Length: ", String.valueOf(directoryEntries.size()));
				Log.i("files Length: ", String.valueOf(files.length));
				
				if(files != null){
					try{
						
						ImageView icon = (ImageView)v.findViewById(R.id.icon);
						TextView filefolderName = (TextView)v.findViewById(R.id.folderName);
						TextView fileType = (TextView)v.findViewById(R.id.fileType);
						TextView items = (TextView)v.findViewById(R.id.item_quality);
						TextView FileFolderSize = (TextView)v.findViewById(R.id.fileSize);
						TextView dateModified = (TextView)v.findViewById(R.id.dateModified);
						
						
						dateModified.setText(String.valueOf(sdf.format(files[position].lastModified())));
						filefolderName.setText(item.get(position).toString());
						if(files[position].isDirectory()){
							Log.i("Ngon chua?", "OK");
							
							filefolderName.setTypeface(null, Typeface.BOLD);
							icon.setBackgroundResource(R.drawable.folder_icon);
							fileType.setText("Folder");
							FileFolderSize.setText("");
							items.setText(FileFolderProperties.getSumOfFolderItems(files[position]));
							Log.i("items", FileFolderProperties.getSumOfFolderItems(files[position]));
						}
						if(files[position].isFile()){
							items.setText("");
							FileFolderSize.setText(FileFolderProperties.getVolumeOfFile(files[position]));
							if(CheckFile.isAPKFile(files[position])){
								icon.setBackgroundResource(R.drawable.apk);
								fileType.setText("apk file");
							}
							else if(CheckFile.isBMPFile(files[position])){
								icon.setBackgroundResource(R.drawable.picture);
								fileType.setText("bmp file");
							}
							else if(CheckFile.isJPEGFile(files[position])){
								icon.setBackgroundResource(R.drawable.picture);
								fileType.setText("bmp file");
							}
							else if(CheckFile.isJPGFile(files[position])){
								icon.setBackgroundResource(R.drawable.picture);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isPNGFile(files[position])){
								icon.setBackgroundResource(R.drawable.picture);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isGIFFile(files[position])){
								icon.setBackgroundResource(R.drawable.picture);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isWordFile(files[position])){
								icon.setBackgroundResource(R.drawable.word_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isPowerpointFile(files[position])){
								icon.setBackgroundResource(R.drawable.ppt_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isExelFile(files[position])){
								icon.setBackgroundResource(R.drawable.excel_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isPDFFile(files[position])){
								icon.setBackgroundResource(R.drawable.pdf_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isMP3File(files[position])){
								icon.setBackgroundResource(R.drawable.mp3_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isWMAFile(files[position])){
								icon.setBackgroundResource(R.drawable.wma_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isHTMLFile(files[position])){
								icon.setBackgroundResource(R.drawable.html_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isXMLFile(files[position])){
								icon.setBackgroundResource(R.drawable.xml_icon);
								fileType.setText("bmp file");
							}
								
							else if(CheckFile.isTXTFile(files[position])){
								icon.setBackgroundResource(R.drawable.txt_icon);
								fileType.setText("bmp file");
							}
								
							else{
								icon.setBackgroundResource(R.drawable.file_icon);
								fileType.setText("File Type");
							}
								
							
						}
						
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				return v;
			}
    	};
    	lv.setAdapter(directoryList);
    	lv.setOnCreateContextMenuListener(this);
    }
    
    public void onItemClick(ListView lv){
    	lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				stopPlayMusicFile();
				int selectionRowID = arg2;
				String selectedFileString = directoryEntries.get(selectionRowID);
				File clickedFile = null;
		        clickedFile = new File(selectedFileString);
		        if(clickedFile.listFiles() != null)
		        		browseTo(clickedFile);
		        else{
		        	if(clickedFile.isDirectory()){
		        		Toast.makeText(SafeFile.this, "don't permit access\nOr Directory empty!", Toast.LENGTH_LONG).show();
		        		titleManager.setText(directoryEntries.get(selectionRowID));
		        	}
		        	else{
		        		titleManager.setText(directoryEntries.get(selectionRowID));
		        		if(CheckFile.isTXTFile(clickedFile)){
		        			Intent intent = new Intent(SafeFile.this, ReadTextFile.class);
		        			intent.putExtra("pathFile", directoryEntries.get(selectionRowID));
		        			startActivityForResult(intent, 2);
		        		}
		        		else if(CheckFile.isMP3File(clickedFile)||CheckFile.isWMAFile(clickedFile))
		        			playMusicFile(clickedFile);
		        		else
		        			launchFile(clickedFile);
		        	}
		        		
		        }
		        	
			}
    		
		});
    }
    
    public void launchFile(File file){
    	Uri uri = Uri.fromFile(file);
    	String extension = getExtension(file.getName());
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(uri, MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension));
    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	try{
    		startActivity(intent);
    	}catch(ActivityNotFoundException e){
    		Toast.makeText(SafeFile.this, "No Application available to view this file", Toast.LENGTH_LONG).show();
    	}
    }
    
    //Start Play music file when click music file
    public void playMusicFile(File mediaFile){
    	Uri uri = Uri.fromFile(mediaFile);
    	mPlayer = MediaPlayer.create(SafeFile.this, uri);
    	mPlayer.start();
    }
    public void stopPlayMusicFile(){
    	if(mPlayer.isPlaying())
    		mPlayer.stop();
    	
    }
    @Override
    public void onStop(){
    	super.onStop();
    	mPlayer.stop();
    }
    
    public String getExtension(String fileName){
    	return (fileName.substring(fileName.length() -3));
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
    	if((keyCode == KeyEvent.KEYCODE_BACK)){
    		if(this.currentDirectory.getParentFile() != null){
    			browseTo(currentDirectory.getParentFile());
    			stopPlayMusicFile();
    		}else{
//        		Toast.makeText(MainActivity.this, "No directory", Toast.LENGTH_SHORT).show();
        		finish();
    		}
    	}
    	return true;
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info;
		try {
			info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		} catch (ClassCastException e) {
			return;
		}

		menu.setHeaderTitle(item.get(item_position_long_clicked = info.position)); //Lay thong tin doi tuong long click (context menu)
		new MenuInflater(getApplication()).inflate(R.menu.safefile_context_menu, menu);
	}
    
    @Override
    public boolean onContextItemSelected(MenuItem item){
    	switch(item.getItemId()){
    	case R.id.Delete:
    		//do something
    		break;
    	case R.id.Cut:
    		//do something
    		break;
    	case R.id.Copy:
    		//do something
    		break;
    	case R.id.Rename:
    		//do something
    		break;
    	case R.id.Upload:
    		//do something
    		File clickedFile = new File(directoryEntries.get(item_position_long_clicked));
    		Log.i("file name", clickedFile.getAbsolutePath());
    		if(clickedFile.isDirectory()){
    			showToast("Not support Backup with a Folder");
    		}else{
//    			showToast("this is a file: " + clickedFile.getAbsolutePath());
    			String stringBase64 = FileStringBase64.FiletoStringBase64(clickedFile);
    			Log.i("File to String base 64: ", stringBase64);
    			Log.i("file path", clickedFile.getAbsolutePath());
    			showBackupFileDialog(stringBase64, clickedFile.getAbsolutePath());
    		}
    		break;
    	case R.id.Properties:
    		//do something
    		break;
    	}
    	return true;
    }
    
    //Option File Explorer Option Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.file_explorer_menu, menu);
        return true;
    }
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case R.id.restore:
			break;
		case R.id.exit:
			finish();
			break;
		}
		return true;
	}
	
	public void showBackupFileDialog(final String data, final String filename) {
		final LinearLayout ll = new LinearLayout(this);
		final EditText inputBoxNotes = new EditText(this, null);

		ll.setOrientation(LinearLayout.VERTICAL);
		ll.setPadding(5, 5, 5, 5);
		ll.addView(inputBoxNotes, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		inputBoxNotes.setHint("Notes");
		new AlertDialog.Builder(this).setView(ll).setIcon(R.drawable.backup_icon).setTitle("Backup Contact").setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				final ProgressDialog pd = showProgressDialog(null, "Please waiting...", false);
				new Thread() {
					public void run() {
						String notes = inputBoxNotes.getText().toString();
						try {
							if (GetWebservice.BackupFile(data, filename, LoginActivity.getUserID(), getDate(DateFormat.DDMMYYYY, "-"), getTime(), notes)) {
								myHandler.post(new Runnable() {
									public void run() {
										showToast("Backup completed");
									}
								});
							} else {
								myHandler.post(new Runnable() {
									public void run() {
										showToast("Backup error!");
									}
								});
							}
						} catch (final Exception e) {
							myHandler.post(new Runnable() {
								public void run() {
									showErrorDialog("Please check again connection." + e.getMessage());
								}
							});
						}
						pd.dismiss();
					}
				}.start();
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int which) {
				d.dismiss();
			}
		}).create().show();
	}
	
}